package com.chen.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.common.Result;
import com.chen.mapper.CommentMapper;
import com.chen.mapper.UserMapper;
import com.chen.pojo.Comment;
import com.chen.pojo.User;
import com.chen.service.Impl.CommentServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author chen

 */
@RestController
@RequestMapping("/comment")
@Api(value = "CommentController",tags = "评论")
public class CommentController {
    @Resource
    private CommentServiceImpl commentService;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserMapper userMapper;

    @GetMapping("/list")
    @ApiOperation("列表")
    public Result CommentList(){
        return commentService.findAllComments();
    }

    @GetMapping("/selectComment/{userId}")
    @ApiOperation("查询某一篇文章所包含的集合")
    public Result selectComment(@PathVariable("userId") int userId){


        return commentService.selectCommentOne(userId);
    }


    @PostMapping("/inserComment")
    @ApiOperation("添加评论")
    public Result inserComment(@RequestBody Comment comment){
        return commentService.insertComment(comment);
    }

    @DeleteMapping("/deleteComment/{id}")
    @ApiOperation("删除评论")
    public Result deleteComment(@PathVariable("id") int id){
        return commentService.deleteComment(id);
    }



    @PutMapping("/updateComment")
    @ApiOperation("更新评论")
    public Result updateComment(Comment comment){
        return commentService.updateComment(comment);
    }



    @GetMapping("/findAvatar")
    @ApiOperation("添加评论")
    public Result findAvatar(){
        List<Comment> comments = commentMapper.selectList(null);
        for (Comment comment : comments) {
            User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, comment.getUsername()));
            if (ObjectUtil.isNotEmpty(user)) {
                if (StrUtil.isNotBlank(user.getAvatar())) {
                    comment.setAvatar(user.getAvatar());
                } else {
                    // 默认一个头像
                    comment.setAvatar("https://img2.baidu.com/it/u=2906052251,1830965798&fm=26&fmt=auto");
                }
            }
        }
        return Result.success(comments);
    }

    @GetMapping("/commentCount")
    @ApiOperation("评论数")
    public Result commentCount(){
        return Result.success(commentMapper.commentCount());
    }

}
